<script setup lang="ts">
import { ContentWrap } from '@/components/ContentWrap'
import { useI18n } from '@/hooks/web/useI18n'
import { Search } from '@/components/Search'
import { Table, TableColumn } from '@/components/Table'
import { ref, reactive, onMounted, computed, watch, h } from 'vue'
import { FormSchema } from '@/components/Form'
import { useSearch } from '@/hooks/web/useSearch'
import {
  ElTag,
  ElMessage,
  ElUpload,
  ElButton,
  ElRadio,
  ElRadioGroup,
  ElInput,
  ElDialog
} from 'element-plus'
import { BaseButton } from '@/components/Button'
import { useRouter } from 'vue-router'
import { Dialog } from '@/components/Dialog'
import { Icon } from '@/components/Icon'
import * as XLSX from 'xlsx'
import {
  queryQtyChargArchInfo,
  exportData,
  updateAbnormalRectification
} from '@/api/electricityAbnormal'

const { t } = useI18n()
const router = useRouter()

// 整改弹窗相关
const rectificationDialogVisible = ref(false)
const currentRow = ref<any>(null)
const rectificationForm = reactive({
  workOrderNo: '',
  rectificationSuggestion: '',
  workOrderStatus: '处理中', // 默认为"处理中"
  actualRectificationDescription: '' // 仅在已处理状态下显示
})

// 打开整改弹窗
const openRectificationDialog = (row) => {
  currentRow.value = row
  // 设置工单编号，使用字符串替换和字符串拼接
  rectificationForm.workOrderNo =
    row.rectificationNo || `YCGD${new Date().getTime().toString().substring(0, 10)}`
  rectificationForm.rectificationSuggestion = row.rectificationSuggestion || '请进行整改处理'
  rectificationForm.workOrderStatus = '处理中'
  rectificationForm.actualRectificationDescription = ''

  rectificationDialogVisible.value = true
}

// 提交整改
const submitRectificationForm = async () => {
  if (!currentRow.value) {
    ElMessage.warning('未找到当前行数据')
    return
  }

  try {
    const submitData = {
      id: currentRow.value.id,
      workOrderNo: rectificationForm.workOrderNo,
      rectificationSuggestion: rectificationForm.rectificationSuggestion,
      workOrderStatus: rectificationForm.workOrderStatus,
      actualRectificationDescription: rectificationForm.actualRectificationDescription,
      // 添加其他需要的字段
      managementUnit: currentRow.value.managementUnit,
      billingMonth: currentRow.value.billingMonth,
      planNo: currentRow.value.planNo,
      userNo: currentRow.value.userNo
    }

    // 调用整改提交API
    const res = await updateAbnormalRectification(submitData)

    if (res && res.data && res.data.code === 200) {
      if (rectificationForm.workOrderStatus === '处理中') {
        ElMessage.success(`整改工单已提交: ${rectificationForm.workOrderNo}`)
        if (currentRow.value) {
          currentRow.value.rectificationStatus = '处理中'
        }
      } else if (rectificationForm.workOrderStatus === '无需处理') {
        ElMessage.success(`整改工单已标记为无需处理: ${rectificationForm.workOrderNo}`)
        if (currentRow.value) {
          currentRow.value.rectificationStatus = '无需处理'
        }
      }

      rectificationDialogVisible.value = false
      // 重新加载数据
      getTableData()
    } else {
      ElMessage.error(res?.data?.msg || '提交失败，请重试')
    }
  } catch (error) {
    console.error('提交整改失败:', error)
    ElMessage.error('提交整改失败: ' + (error instanceof Error ? error.message : '未知错误'))
  }
}

// 取消整改
const cancelRectification = () => {
  rectificationDialogVisible.value = false
}

// 搜索相关
const { searchRegister, searchMethods } = useSearch()
const searchRef = ref(null)
const { setSchema, setProps, getFormData } = searchMethods

// 搜索表单配置
const schema = reactive<FormSchema[]>([
  {
    field: 'managementUnit',
    label: '管理单位',
    component: 'Input',
    componentProps: {
      placeholder: '请输入管理单位'
    }
  },
  {
    field: 'billingMonth',
    label: '量费年月',
    component: 'DatePicker',
    componentProps: {
      type: 'month',
      placeholder: '请选择量费年月',
      valueFormat: 'YYYY-MM'
    }
  },
  {
    field: 'customerCategory',
    label: '客户分类',
    component: 'Select',
    componentProps: {
      placeholder: '请选择客户分类',
      options: [
        {
          label: '全部',
          value: ''
        },
        {
          label: '居民',
          value: '1'
        },
        {
          label: '商业',
          value: '2'
        },
        {
          label: '工业',
          value: '3'
        },
        {
          label: '农业',
          value: '4'
        },
        {
          label: '其他',
          value: '5'
        }
      ]
    }
  },
  {
    field: 'marketPropertyType',
    label: '市场化属性分类',
    component: 'Select',
    componentProps: {
      placeholder: '请选择市场化属性分类',
      options: [
        {
          label: '全部',
          value: ''
        },
        {
          label: '全电量市场',
          value: '1'
        },
        {
          label: '部分市场',
          value: '2'
        },
        {
          label: '非市场',
          value: '3'
        }
      ]
    }
  },
  {
    field: 'powerUsageType',
    label: '用电类别',
    component: 'Select',
    componentProps: {
      placeholder: '请选择用电类别',
      options: [
        {
          label: '全部',
          value: ''
        },
        {
          label: '居民用电',
          value: '1'
        },
        {
          label: '商业用电',
          value: '2'
        },
        {
          label: '工业用电',
          value: '3'
        },
        {
          label: '农业用电',
          value: '4'
        }
      ]
    }
  },
  {
    field: 'rectificationStatus',
    label: '整改状态',
    component: 'Select',
    componentProps: {
      placeholder: '请选择整改状态',
      options: [
        {
          label: '全部',
          value: ''
        },
        {
          label: '未处理',
          value: '0'
        },
        {
          label: '处理中',
          value: '1'
        },
        {
          label: '已处理',
          value: '2'
        },
        {
          label: '无需处理',
          value: '3'
        }
      ]
    }
  },
  {
    field: 'abnormalType',
    label: '异常类型',
    component: 'Cascader',
    componentProps: {
      placeholder: '请选择异常类型',
      props: {
        expandTrigger: 'hover',
        checkStrictly: true,
        emitPath: false
      },
      options: [
        {
          label: '全部',
          value: '00'
        },
        {
          label: '档案异常',
          value: '01',
          children: [
            {
              label: '定价策略信息异常',
              value: '0101'
            },
            {
              label: '计费关系异常',
              value: '0102'
            },
            {
              label: '转供关系异常',
              value: '0103'
            },
            {
              label: '电价信息异常',
              value: '0104'
            },
            {
              label: '电源信息异常',
              value: '0106'
            },
            {
              label: '线路信息异常',
              value: '0107'
            }
          ]
        },
        {
          label: '量费异常',
          value: '03',
          children: [
            {
              label: '主分表扣减异常',
              value: '0301'
            },
            {
              label: '变损电量异常',
              value: '0302'
            },
            {
              label: '时段电量异常',
              value: '0303'
            },
            {
              label: '线损电量异常',
              value: '0304'
            }
          ]
        }
      ]
    }
  }
])

// tab栏相关
const activeTab = ref('all')
const tabList = [
  { key: 'all', name: '全部', count: 100 },
  { key: 'pending', name: '未处理', count: 25 },
  { key: 'processing', name: '处理中', count: 25 },
  { key: 'processed', name: '已处理', count: 25 },
  { key: 'unnecessary', name: '无需处理', count: 25 }
]

// 切换tab
const handleTabChange = (tab) => {
  activeTab.value = tab
  // 根据tab重新加载数据
  pagination.currentPage = 1
  getTableData()
}

// 表格相关
const columns: TableColumn[] = [
  {
    field: 'rectificationNo',
    label: '整改单编号',
    width: 150,
    fixed: 'left'
  },
  {
    field: 'managementUnit',
    label: '管理单位',
    width: 150
  },
  {
    field: 'billingMonth',
    label: '量费年月',
    width: 120
  },
  {
    field: 'rectificationStatus',
    label: '整改状态',
    width: 120,
    formatter: (row) => {
      const statusMap = {
        未处理: 'danger',
        处理中: 'warning',
        已处理: 'success',
        无需处理: 'info'
      }
      return h(ElTag, { type: statusMap[row.rectificationStatus] }, () => row.rectificationStatus)
    }
  },
  {
    field: 'abnormalCategory',
    label: '异常类别',
    width: 120
  },
  {
    field: 'abnormalDetails',
    label: '异常说明',
    width: 200
  },
  {
    field: 'rectificationSuggestion',
    label: '整改建议',
    width: 200
  },
  {
    field: 'action',
    label: '操作',
    width: 160,
    fixed: 'right',
    slots: {
      default: (data: any) => {
        return [
          h(
            BaseButton,
            {
              type: 'primary',
              link: true,
              onClick: () => openDetailDialog(data.row)
            },
            '查看详情'
          ),
          h('span', { style: 'margin: 0 5px' }, '|'),
          h(
            BaseButton,
            {
              type: 'success',
              link: true,
              onClick: () => openRectificationDialog(data.row)
            },
            '整改'
          )
        ]
      }
    }
  }
]

// 详情弹窗相关
const detailDialogVisible = ref(false)
const currentDetail = ref<any>(null)

// 打开详情弹窗
const openDetailDialog = (row: any) => {
  // 模拟获取更多详细数据
  currentDetail.value = {
    ...row,
    // 添加更多详细信息
    abnormalType: '计费关系异常',
    contractCapacity: 'xxxxxxxx',
    operationCapacity: 'xxxxxxxx',
    accountingPackageNo: 'xxxxxxxx',
    industryCategory: 'xxxxxxxx'
  }
  detailDialogVisible.value = true
}

// 关闭详情弹窗
const closeDetailDialog = () => {
  detailDialogVisible.value = false
}

// 表格数据和加载状态
const loading = ref(true)
const tableDataList = ref<any[]>([])
const allDataList = ref<any[]>([]) // 存储所有数据，用于分页
const pagination = reactive({
  total: 0,
  pageSize: 10,
  currentPage: 1
})

// 更新分页数据
const updatePagedData = () => {
  const start = (pagination.currentPage - 1) * pagination.pageSize
  const end = start + pagination.pageSize

  if (allDataList.value.length > 0) {
    // 确保不会超出数组范围
    const actualEnd = Math.min(end, allDataList.value.length)
    tableDataList.value = allDataList.value.slice(start, actualEnd)
  } else {
    tableDataList.value = []
  }
}

// 获取表格数据函数
const getTableData = async () => {
  loading.value = true
  try {
    const formData = getFormData()
    // 添加整改状态参数
    formData.isRectification = true

    console.log('查询条件:', formData)

    // 调用API接口获取数据
    const { data } = await queryQtyChargArchInfo(formData)
    console.log('API返回数据:', data)

    // 保存数据到allDataList
    if (data && Array.isArray(data.data)) {
      allDataList.value = data.data
      pagination.total = data.total || data.data.length
    } else {
      allDataList.value = []
      pagination.total = 0
      console.warn('API返回数据格式不符合预期', data)
    }

    // 更新分页数据
    updatePagedData()

    loading.value = false
  } catch (error) {
    loading.value = false
    console.error('获取数据失败:', error)
    ElMessage.error('获取数据失败: ' + (error instanceof Error ? error.message : '未知错误'))
    allDataList.value = []
    tableDataList.value = []
    pagination.total = 0
  }
}

// 导出数据
const handleExport = async () => {
  try {
    const formData = getFormData()
    // 添加整改状态参数
    formData.isRectification = true

    ElMessage.info('正在导出数据，请稍候...')

    // 调用导出API
    const res = await exportData(formData)

    // 处理二进制数据
    const blob = new Blob([res.data], {
      type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
    })

    // 创建下载链接
    const link = document.createElement('a')
    const url = URL.createObjectURL(blob)
    const date = new Date().toISOString().split('T')[0]
    link.href = url
    link.download = `电费异常整改数据_${date}.xlsx`
    document.body.appendChild(link)
    link.click()
    document.body.removeChild(link)
    URL.revokeObjectURL(url)

    ElMessage.success('数据导出成功')
  } catch (error) {
    console.error('导出数据失败:', error)
    ElMessage.error('导出数据失败，请重试')
  }
}

// 搜索处理
const handleSearch = () => {
  const formData = getFormData()
  console.log('搜索条件:', formData)

  // 重新获取数据
  pagination.currentPage = 1
  getTableData()
}

// 重置搜索
const handleReset = () => {
  pagination.currentPage = 1
  getTableData()
}

// 分页变化
const handlePageChange = (page: number) => {
  updatePagedData()
}

// 页大小变化
const handleSizeChange = (size: number) => {
  pagination.currentPage = 1
  updatePagedData()
}

// 在组件挂载后注册Search组件
onMounted(() => {
  // 注册搜索组件
  if (searchRef.value) {
    searchRegister(searchRef.value)
  }
  // 初始化表格数据
  getTableData()
})
</script>

<template>
  <ContentWrap title="电费异常整改">
    <!-- 搜索栏 -->
    <Search ref="searchRef" :schema="schema" @search="handleSearch" @reset="handleReset" />

    <div class="table-operations">
      <!-- 导出按钮 -->
      <ElButton type="success" @click="handleExport" class="operation-button">
        <Icon icon="vi-ep:download" class="mr-5px" />
        导出数据
      </ElButton>
    </div>

    <!-- 状态选项卡 -->
    <div class="status-tabs">
      <div
        v-for="tab in tabList"
        :key="tab.key"
        :class="['status-tab', { active: activeTab === tab.key }]"
        @click="handleTabChange(tab.key)"
      >
        {{ tab.name }} <span class="tab-count">({{ tab.count }})</span>
      </div>
    </div>

    <!-- 表格区域 -->
    <Table
      v-model:pageSize="pagination.pageSize"
      v-model:currentPage="pagination.currentPage"
      :loading="loading"
      :data="tableDataList"
      :columns="columns"
      :pagination="{
        total: pagination.total,
        pageSize: pagination.pageSize,
        currentPage: pagination.currentPage,
        pageSizes: [10, 20, 50, 100],
        background: true
      }"
      @pageChange="handlePageChange"
      @sizeChange="handleSizeChange"
    />
  </ContentWrap>

  <!-- 整改弹窗 -->
  <Dialog v-model="rectificationDialogVisible" title="整改" width="500px" maxHeight="500">
    <div class="rectification-form">
      <div class="form-item">
        <span class="label">工单编号：</span>
        <span>{{ rectificationForm.workOrderNo }}</span>
        <span class="copy-btn" @click="() => ElMessage.success('已复制工单编号')">复制</span>
      </div>

      <div class="form-item">
        <span class="label">整改建议：</span>
        <span>{{ rectificationForm.rectificationSuggestion }}</span>
      </div>

      <div class="form-item">
        <span class="label">工单状态：</span>
        <ElRadioGroup v-model="rectificationForm.workOrderStatus">
          <ElRadio label="处理中">处理中</ElRadio>
          <ElRadio label="无需处理">无需处理</ElRadio>
        </ElRadioGroup>
      </div>

      <div class="form-item" v-if="rectificationForm.workOrderStatus === '无需处理'">
        <span class="label">实际整改说明：</span>
        <ElInput
          v-model="rectificationForm.actualRectificationDescription"
          type="textarea"
          :rows="3"
          placeholder="请输入实际整改说明"
        />
      </div>
    </div>

    <template #footer>
      <ElButton @click="cancelRectification">取 消</ElButton>
      <ElButton type="primary" @click="submitRectificationForm">提 交</ElButton>
    </template>
  </Dialog>

  <!-- 详情弹窗 -->
  <ElDialog
    v-model="detailDialogVisible"
    title="异常详情"
    width="900px"
    :before-close="closeDetailDialog"
    destroy-on-close
    class="detail-dialog"
  >
    <div class="detail-container">
      <div class="detail-row">
        <div class="detail-item">
          <div class="detail-label">整改单编号：</div>
          <div class="detail-value">{{ currentDetail?.rectificationNo }}</div>
        </div>
        <div class="detail-item">
          <div class="detail-label">管理单位：</div>
          <div class="detail-value">{{ currentDetail?.managementUnit }}</div>
        </div>
        <div class="detail-item">
          <div class="detail-label">量费年月：</div>
          <div class="detail-value">{{ currentDetail?.billingMonth }}</div>
        </div>
      </div>

      <div class="detail-row">
        <div class="detail-item">
          <div class="detail-label">异常类别：</div>
          <div class="detail-value">{{ currentDetail?.abnormalCategory }}</div>
        </div>
        <div class="detail-item">
          <div class="detail-label">异常说明：</div>
          <div class="detail-value">{{ currentDetail?.abnormalDetails }}</div>
        </div>
        <div class="detail-item">
          <div class="detail-label">整改建议：</div>
          <div class="detail-value">{{ currentDetail?.rectificationSuggestion }}</div>
        </div>
      </div>

      <div class="detail-row">
        <div class="detail-item">
          <div class="detail-label">整改状态：</div>
          <div class="detail-value">{{ currentDetail?.rectificationStatus }}</div>
        </div>
        <div class="detail-item">
          <div class="detail-label">客户分类：</div>
          <div class="detail-value">{{ currentDetail?.customerCategory }}</div>
        </div>
        <div class="detail-item">
          <div class="detail-label">用电类别：</div>
          <div class="detail-value">{{ currentDetail?.powerUsageType }}</div>
        </div>
      </div>

      <div class="detail-row">
        <div class="detail-item">
          <div class="detail-label">市场化属性：</div>
          <div class="detail-value">{{ currentDetail?.marketPropertyType }}</div>
        </div>
        <div class="detail-item">
          <div class="detail-label">核算包编号：</div>
          <div class="detail-value">{{ currentDetail?.accountingPackageNo }}</div>
        </div>
        <div class="detail-item">
          <div class="detail-label">计划编号：</div>
          <div class="detail-value">{{ currentDetail?.planNo }}</div>
        </div>
      </div>
    </div>
  </ElDialog>
</template>

<style lang="scss" scoped>
.rectification-form {
  padding: 15px 0;

  .form-item {
    margin-bottom: 20px;

    .label {
      display: inline-block;
      width: 100px;
      text-align: right;
      margin-right: 10px;
      font-weight: 500;
    }

    .copy-btn {
      margin-left: 10px;
      color: #409eff;
      cursor: pointer;
    }
  }
}

.table-operations {
  display: flex;
  justify-content: flex-end;
  margin-bottom: 16px;
}

.operation-button {
  margin-left: 8px;
}

/* 状态选项卡样式 */
.status-tabs {
  display: flex;
  margin-bottom: 16px;
  border-bottom: 1px solid #f0f0f0;
  background-color: #fff;
  padding: 0 10px;
}

.status-tab {
  padding: 12px 16px;
  cursor: pointer;
  position: relative;
  font-size: 14px;
  color: #606266;
  transition: all 0.3s;
}

.status-tab:hover {
  color: #409eff;
}

.status-tab.active {
  color: #409eff;
  font-weight: 500;
}

.status-tab.active:after {
  content: '';
  position: absolute;
  bottom: -1px;
  left: 50%;
  width: 60%;
  height: 2px;
  background-color: #409eff;
  transform: translateX(-50%);
}

.tab-count {
  color: #909399;
  margin-left: 2px;
}

/* 详情弹窗样式 */
.detail-container {
  width: 100%;
  padding: 16px;
}

.detail-row {
  display: flex;
  margin-bottom: 16px;
  width: 100%;
  border-bottom: 1px solid #f0f0f0;
  padding-bottom: 12px;
}

.detail-item {
  display: flex;
  flex: 1;
  min-width: 0;
  padding-right: 16px;
}

.detail-label {
  font-weight: bold;
  color: #606266;
  min-width: 100px;
  flex-shrink: 0;
}

.detail-value {
  flex: 1;
  color: #303133;
  word-break: break-all;
}
</style>
